package com.huawei.spare.part.replace.ssh;

import net.schmizz.keepalive.KeepAliveProvider;
import net.schmizz.sshj.DefaultConfig;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.common.LoggerFactory;
import net.schmizz.sshj.common.StreamCopier;
import net.schmizz.sshj.connection.channel.direct.Session;
import net.schmizz.sshj.connection.channel.direct.Session.Shell;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/** A very rudimentary psuedo-terminal based on console I/O. */
class ShellPTY {

    public static void main(String... args)
            throws IOException {

        DefaultConfig defaultConfig = new DefaultConfig();
        defaultConfig.setKeepAliveProvider(KeepAliveProvider.KEEP_ALIVE);
        final SSHClient ssh = new SSHClient(defaultConfig);
        ssh.addHostKeyVerifier(new PromiscuousVerifier());
        ssh.connect("115.159.160.190");
        ssh.authPassword("root", "!QAZ2wsx#EDC");
        try {
            final Session session = ssh.startSession();
            ssh.getConnection().getKeepAlive().setKeepAliveInterval(5);
            try {
                session.allocateDefaultPTY();
                final Shell shell = session.startShell();

                new StreamCopier(shell.getInputStream(), System.out, LoggerFactory.DEFAULT)
                        .bufSize(shell.getLocalMaxPacketSize())
                        .spawn("stdout");
                new StreamCopier(shell.getErrorStream(), System.err, LoggerFactory.DEFAULT)
                        .bufSize(shell.getLocalMaxPacketSize())
                        .spawn("stderr");

                // Now make System.in act as stdin. To exit, hit Ctrl+D (since that results in an EOF on System.in)
                // This is kinda messy because java only allows console input after you hit return
                // But this is just an example... a GUI app could implement a proper PTY
                ByteArrayInputStream in = new ByteArrayInputStream("".getBytes());
                new StreamCopier(in, shell.getOutputStream(), LoggerFactory.DEFAULT)
                        .bufSize(shell.getRemoteMaxPacketSize())
                        .copy();

                shell.join();
                System.out.println("get-here");
//                shell.getOutputStream().send("python /root/spare.py".getBytes());
//                in.read("cd /root".getBytes());

            } finally {
                session.close();
            }

        } finally {
            ssh.disconnect();
        }
    }

}
